#include "height_controller.h"
#include "model/height_model.h"

HeightController::HeightController(View* v,Model* m)
	:Controller2D(v,m){
}

HeightController::~HeightController(){}

void HeightController::keyboard(unsigned char key,float x ,float y){
	if(key=='c'){
		// La curva debe terminar a la misma altura donde comeno
		HeightModel& curve = dynamic_cast<HeightModel&>(*model);

		// No puede hacerse nada si no existe la cantidad de puntos necesarios
		if(curve.controlSize()<4)
			return;

		Point p = curve.getLast();
		p+=HeightModel::offset;

		// No se debe nivelar nada si ya esta nivelado
		if(p.x2==curve.getFirst().x2)
			return;

		p.x2 = curve.getFirst().x2;
	    curve.addPoint(p);
	    curve.finalizeCurve();
	    calculatePoints();
	}
}

void HeightController::mousePressed(int key,int state,float x ,float y){
	HeightModel& hmodel = dynamic_cast<HeightModel&>(*model);
	Controller2D::mousePressed(key,state,x,y);

	//Si el punto esta debajo del nivel de referencia se lo pone
	// sobre el mismo
	if(y<hmodel.getGroundRef())
		y= hmodel.getGroundRef();

	if (!this->drag.first && key==GLUT_LEFT_BUTTON && state==GLUT_DOWN){
		hmodel.addPoint(Point(x,y,0));
		if(hmodel.controlSize()>1)
			calculatePoints();
	}else if (this->drag.first && key==GLUT_RIGHT_BUTTON && state==GLUT_DOWN){
		hmodel.removePoint(this->drag.second);
		this->drag=std::pair<bool,Point>(false,Point(0,0));
		hmodel.calculatePoints();
	}else if(this->drag.first && key==GLUT_LEFT_BUTTON && state==GLUT_UP){
		std::pair<bool,Point>(false,Point(0,0));
		Point p(x,y);
		hmodel.movePoint(drag.second,p);
		calculatePoints();
		this->drag=std::pair<bool,Point>(false,Point(0,0));
	}
}
